import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../core/gitcode_api.dart';

/// 用户详情页面
/// 展示用户的完整信息，包括头像、简介、统计信息等
class UserDetailPage extends StatefulWidget {
  const UserDetailPage({
    super.key,
    required this.username,
    this.token,
  });

  final String username;
  final String? token;

  @override
  State<UserDetailPage> createState() => _UserDetailPageState();
}

class _UserDetailPageState extends State<UserDetailPage> {
  final GitCodeApiClient _client = GitCodeApiClient();
  GitCodeUser? _user;
  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _loadUserDetail();
  }

  Future<void> _loadUserDetail() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final user = await _client.fetchUser(
        widget.username,
        personalToken: widget.token,
      );
      setState(() {
        _user = user;
        _isLoading = false;
      });
    } on GitCodeApiException catch (e) {
      setState(() {
        _errorMessage = e.message;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _errorMessage = '加载失败：$e';
        _isLoading = false;
      });
    }
  }

  Future<void> _openUrl(String? url) async {
    if (url == null || url.isEmpty) return;
    final uri = Uri.tryParse(url);
    if (uri != null && await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(_user?.name ?? _user?.login ?? widget.username),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _errorMessage != null
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.error_outline,
                        size: 64,
                        color: theme.colorScheme.error,
                      ),
                      const SizedBox(height: 16),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 32),
                        child: Text(
                          _errorMessage!,
                          style: TextStyle(color: theme.colorScheme.onErrorContainer),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      const SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: _loadUserDetail,
                        child: const Text('重试'),
                      ),
                    ],
                  ),
                )
              : _user == null
                  ? const Center(child: Text('用户信息为空'))
                  : SingleChildScrollView(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 用户头像和基本信息
                          Center(
                            child: Column(
                              children: [
                                CircleAvatar(
                                  radius: 60,
                                  backgroundImage: _user!.avatarUrl.isNotEmpty
                                      ? NetworkImage(_user!.avatarUrl)
                                      : null,
                                  backgroundColor:
                                      theme.colorScheme.surfaceContainerHighest,
                                  child: _user!.avatarUrl.isEmpty
                                      ? Icon(
                                          Icons.person,
                                          size: 60,
                                          color: theme
                                              .colorScheme.onSurfaceVariant,
                                        )
                                      : null,
                                ),
                                const SizedBox(height: 16),
                                Text(
                                  _user!.name ?? _user!.login,
                                  style: theme.textTheme.headlineSmall?.copyWith(
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                if (_user!.name != null &&
                                    _user!.name != _user!.login) ...[
                                  const SizedBox(height: 4),
                                  Text(
                                    '@${_user!.login}',
                                    style: theme.textTheme.bodyMedium?.copyWith(
                                      color: theme.colorScheme.onSurfaceVariant,
                                    ),
                                  ),
                                ],
                              ],
                            ),
                          ),
                          const SizedBox(height: 32),
                          // 个人简介
                          if (_user!.bio != null && _user!.bio!.isNotEmpty) ...[
                            Text(
                              '简介',
                              style: theme.textTheme.titleMedium?.copyWith(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              _user!.bio!,
                              style: theme.textTheme.bodyMedium,
                            ),
                            const SizedBox(height: 24),
                          ],
                          // 统计信息
                          Text(
                            '统计信息',
                            style: theme.textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 12),
                          Row(
                            children: [
                              Expanded(
                                child: _buildStatCard(
                                  context,
                                  '仓库',
                                  _user!.publicRepos?.toString() ?? '0',
                                  Icons.folder_outlined,
                                ),
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: _buildStatCard(
                                  context,
                                  '粉丝',
                                  _user!.followers?.toString() ?? '0',
                                  Icons.people_outline,
                                ),
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: _buildStatCard(
                                  context,
                                  '关注',
                                  _user!.following?.toString() ?? '0',
                                  Icons.person_add_outlined,
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 24),
                          // 其他信息
                          Text(
                            '其他信息',
                            style: theme.textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 12),
                          if (_user!.createdAt != null)
                            _buildInfoRow(
                              context,
                              Icons.calendar_today,
                              '注册时间',
                              _formatDate(_user!.createdAt!),
                            ),
                          if (_user!.htmlUrl != null &&
                              _user!.htmlUrl!.isNotEmpty)
                            _buildInfoRow(
                              context,
                              Icons.link,
                              '主页链接',
                              _user!.htmlUrl!,
                              onTap: () => _openUrl(_user!.htmlUrl),
                            ),
                        ],
                      ),
                    ),
    );
  }

  Widget _buildStatCard(
    BuildContext context,
    String label,
    String value,
    IconData icon,
  ) {
    final theme = Theme.of(context);
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Icon(icon, size: 32, color: theme.colorScheme.primary),
            const SizedBox(height: 8),
            Text(
              value,
              style: theme.textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              label,
              style: theme.textTheme.bodySmall?.copyWith(
                color: theme.colorScheme.onSurfaceVariant,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoRow(
    BuildContext context,
    IconData icon,
    String label,
    String value, {
    VoidCallback? onTap,
  }) {
    final theme = Theme.of(context);
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: InkWell(
        onTap: onTap,
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              Icon(icon, color: theme.colorScheme.primary),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      label,
                      style: theme.textTheme.bodySmall?.copyWith(
                color: theme.colorScheme.onSurfaceVariant,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      value,
                      style: theme.textTheme.bodyMedium,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
              if (onTap != null)
                Icon(
                  Icons.open_in_new,
                  size: 20,
                  color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.6),
                ),
            ],
          ),
        ),
      ),
    );
  }

  String _formatDate(String dateString) {
    try {
      final date = DateTime.parse(dateString);
      return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    } catch (e) {
      return dateString.length > 10
          ? dateString.substring(0, 10)
          : dateString;
    }
  }
}

